﻿<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="indexTitle" ContentPlaceHolderID="TitleContent" runat="server">ExploAzure - Storage Manager</asp:Content>
<asp:Content ID="indexScript" ContentPlaceHolderID="ScriptContent" runat="server">
<script type="text/javascript">
var account_needed = <%=(Session["AccountName"] == null) ? "true" : "false" %>;
var tables_grid = null;
var queues_grid = null;
var blobs_grid = null;
var queue_messages_grid = null;
var table_entities_grid = null;
var upload_dialog = null;
var upload_binary_msg_dialog = null;
var help_dialog = null;
var account_dialog = null;
var entities_dialogs = new Object();

Ext.onReady(function()
{
	Ext.BLANK_IMAGE_URL = '../../Content/ext/resources/images/default/s.gif';

	blob_container_selected = function(selection_model)
	{
		var row = blob_containers_grid.getSelectionModel().getSelected();

		if (!row)
		{
			blobs_grid.getStore().removeAll();
			blobs_grid.setTitle('BLOBs - container not selected');
			blobs_grid.containerName = null;
			Ext.getCmp('deleteblobcontainerbutton').setDisabled(true);
			Ext.getCmp('uploaddialogbutton').setDisabled(true);
			Ext.getCmp('refreshblobsbutton').setDisabled(true);
		}
		else
		{
			blobs_grid.getStore().reload({ params: { container: row.data.name} });
			blobs_grid.setTitle('BLOBs in [' + row.data.name + '] container');
			blobs_grid.containerName = row.data.name;
			Ext.getCmp('deleteblobcontainerbutton').setDisabled(false);
			Ext.getCmp('uploaddialogbutton').setDisabled(false);
			Ext.getCmp('refreshblobsbutton').setDisabled(false);
		}
	};

	blob_selected = function(selection_model)
	{
		var row = blobs_grid.getSelectionModel().getSelected();

		if (!row)
			Ext.getCmp('deleteblobbutton').setDisabled(true);
		else Ext.getCmp('deleteblobbutton').setDisabled(false);
	};

	table_selected = function(selection_model)
	{
		var row = tables_grid.getSelectionModel().getSelected();

		if (!row)
		{
			table_entities_grid.getStore().removeAll();
			table_entities_grid.setTitle('Entities - table not selected');
			table_entities_grid.tableName = null;
			Ext.getCmp('deletetablebutton').setDisabled(true);
			Ext.getCmp('createentity').setDisabled(true);
		}
		else
		{
			table_entities_grid.getStore().reload({ params: { table: row.data.name} });
			table_entities_grid.setTitle('Entities in [' + row.data.name + '] table');
			table_entities_grid.tableName = row.data.name;
			Ext.getCmp('deletetablebutton').setDisabled(false);
			Ext.getCmp('createentity').setDisabled(false);
		}
	};

	table_entity_selected = function(selection_model)
	{
		var row = tables_grid.getSelectionModel().getSelected();

		if (!row)
			Ext.getCmp('deleteentity').setDisabled(true);
		else Ext.getCmp('deleteentity').setDisabled(false);
	};

	queue_selected = function(selection_model)
	{
		var row = queues_grid.getSelectionModel().getSelected();

		if (!row)
		{
			queue_messages_grid.getStore().removeAll();
			queue_messages_grid.setTitle('Top messages - queue not selected');
			queue_messages_grid.queueName = null;
			Ext.getCmp('refreshqueuemessagesbutton').setDisabled(true);
			Ext.getCmp('deletequeuebutton').setDisabled(true);
			Ext.getCmp('createqueuemessage').setDisabled(true);
			Ext.getCmp('uploadbinarymsgbutton').setDisabled(true);
			Ext.getCmp('getqueuemessage').setDisabled(true);
		}
		else
		{
			queue_messages_grid.getStore().reload({ params: { name: row.data.name} });
			queue_messages_grid.setTitle('Top messages in [' + row.data.name + '] queue');
			queue_messages_grid.queueName = row.data.name;
			Ext.getCmp('refreshqueuemessagesbutton').setDisabled(false);
			Ext.getCmp('deletequeuebutton').setDisabled(false);
			Ext.getCmp('createqueuemessage').setDisabled(false);
			Ext.getCmp('uploadbinarymsgbutton').setDisabled(false);
			Ext.getCmp('getqueuemessage').setDisabled(false);
		}
	};

	var blob_containers_sm = new Ext.grid.RowSelectionModel({ singleSelect: true });
	blob_containers_sm.on('selectionchange', blob_container_selected);

	var blob_containers_grid = new Ext.grid.GridPanel(
	{
		id: 'blobContainers',
		title: 'Blob containers',
		iconCls: 'box-icon',
		padding: '0 0 0 0',
		margin: '5 5 5 5',
		frame: false,
		border: false,
		stripeRows: true,
		viewConfig: { forceFit: true },
		store: new Ext.data.Store(
		{
			proxy: new Ext.data.HttpProxy({ url: '/Home/ListBlobContainers' }),
			reader: new Ext.data.JsonReader(
				{ root: 'blob_containers', totalProperty: 'total' },
				Ext.data.Record.create([{ name: 'name' }, { name: 'uri' }, { name: 'modified' }, { name: 'ispublic'}])
			),
			sortInfo: { field: 'name', direction: "ASC" },
			remoteSort: false
		}),
		cm: new Ext.grid.ColumnModel(
		[
			{ id: 'name', header: 'Name', dataIndex: 'name', sortable: true, width: 240 },
			{ id: 'uri', header: 'Uri', dataIndex: 'uri', sortable: true, width: 300, xtype: 'templatecolumn', tpl: new Ext.XTemplate('<a href="{uri}?comp=list" target="_blank">{uri}?comp=list</a>') },
			{ id: 'modified', header: 'Modified', dataIndex: 'modified', sortable: true, width: 150 },
			{ id: 'ispublic', header: 'Public', dataIndex: 'ispublic', sortable: false, width: 50, xtype: 'booleancolumn', falseText: 'No', trueText: 'Yes' }
		]),
		autoExpandColumn: 'uri',
		sm: blob_containers_sm,
		bbar: new Ext.Toolbar(
		{
			margins: '5 5 5 5',
			items: [
			{
				iconCls: 'refresh-icon',
				handler: function(button, event)
				{
					blob_containers_grid.getStore().reload();
				}
			},
			'-',
			{
				xtype: 'textfield',
				id: 'newblobcontainername',
				emptyText: 'Enter container name'
			},
			' ',
			{
				xtype: 'checkbox',
				id: 'newblobcontainerispublic',
				checked: false
			},
			' ',
			'public',
			' ',
			{
				text: 'Create BLOB container',
				iconCls: 'add-icon',
				handler: function(button, event)
				{
					Ext.Ajax.request(
					{
						url: '/Home/CreateBlobContainer',
						method: 'POST',
						params:
						{
							name: Ext.getCmp('newblobcontainername').getValue(),
							isPublic: Ext.getCmp('newblobcontainerispublic').getValue()
						},
						success: function(response)
						{
							var result = Ext.decode(response.responseText);

							if (result.rc)
								blob_containers_grid.getStore().reload();
							else Ext.Msg.alert('Failed to create BLOB container', result.text);
						}
					});
				}
			},
			'-',
			{
				id: 'deleteblobcontainerbutton',
				text: 'Delete selected',
				iconCls: 'delete-icon',
				disabled: true,
				handler: function(button, event)
				{
					var rec = blob_containers_grid.getSelectionModel().getSelected();

					if (!rec)
						return;

					Ext.Ajax.request(
					{
						url: '/Home/DeleteBlobContainer',
						method: 'DELETE',
						params:
						{
							name: rec.data.name
						},
						success: function(response)
						{
							var result = Ext.decode(response.responseText);

							if (result.rc)
								blob_containers_grid.getStore().reload();
							else Ext.Msg.alert('Failed to delete BLOB container', result.text);
						}
					});
				}
			}
			]
		})
	});

	function open_upload_dialog(button)
	{
		if (!upload_dialog)
		{
			upload_dialog = new Ext.ux.UploadDialog.Dialog(
			{
				title: 'Upload BLOBs',
				url: '/Home/CreateBlob',
				reset_on_hide: true,
				allow_close_on_upload: true,
				upload_autostart: false,
				post_var_name: 'upload'
			});

			upload_dialog.on('uploadsuccess', function() { blobs_grid.getStore().reload(); });
		}

		upload_dialog.setBaseParams({ container: blobs_grid.containerName });

		upload_dialog.show(button.getEl());
	}

	function open_upload_binary_msg_dialog(button)
	{
		if (!upload_binary_msg_dialog)
		{
			upload_binary_msg_dialog = new Ext.ux.UploadDialog.Dialog(
			{
				title: 'Upload binary messages',
				url: '/Home/CreateBinaryMessage',
				reset_on_hide: true,
				allow_close_on_upload: true,
				upload_autostart: false,
				post_var_name: 'upload'
			});

			upload_binary_msg_dialog.on('uploadsuccess', function() { queue_messages_grid.getStore().reload(); });
		}

		upload_binary_msg_dialog.setBaseParams({ queue: queue_messages_grid.queueName });

		upload_binary_msg_dialog.show(button.getEl());
	}

	var blobs_sm = new Ext.grid.RowSelectionModel({ singleSelect: true });
	blobs_sm.on('selectionchange', blob_selected);

	blobs_grid = new Ext.grid.GridPanel(
	{
		id: 'blobs',
		title: 'BLOBs - container not selected',
		iconCls: 'blob-icon',
		padding: '0 0 0 0',
		margin: '5 5 5 5',
		border: false,
		frame: false,
		stripeRows: true,
		viewConfig: { forceFit: true },
		store: new Ext.data.Store(
		{
			proxy: new Ext.data.HttpProxy({ url: '/Home/ListBlobs' }),
			reader: new Ext.data.JsonReader(
				{ root: 'blobs', totalProperty: 'total' },
				Ext.data.Record.create([{ name: 'name' }, { name: 'uri' }, { name: 'modified' }, { name: 'content_type' }, { name: 'content_length' }, { name: 'content_lang' }, { name: 'content_encoding'}])
			),
			sortInfo: { field: 'name', direction: "ASC" },
			remoteSort: false
		}),
		cm: new Ext.grid.ColumnModel(
		[
			{ id: 'name', header: 'Name', dataIndex: 'name', sortable: true, width: 240, xtype: 'templatecolumn', tpl: new Ext.XTemplate('<a href="{uri}" target="_blank">{name}</a>') },
			{ id: 'uri', header: 'Uri', dataIndex: 'uri', sortable: true, width: 300, xtype: 'templatecolumn', tpl: new Ext.XTemplate('<a href="{uri}" target="_blank">{uri}</a>') },
			{ id: 'modified', header: 'Modified', dataIndex: 'modified', sortable: true, width: 150 },
			{ id: 'content_type', header: 'Content type', dataIndex: 'content_type', sortable: false, width: 100 },
			{ id: 'content_length', header: 'Content length', dataIndex: 'content_length', sortable: true, width: 80 },
			{ id: 'content_lang', header: 'Content language', dataIndex: 'content_lang', sortable: true, width: 100 },
			{ id: 'content_encoding', header: 'Encoding', dataIndex: 'content_encoding', sortable: true, width: 100 }
		]),
		autoExpandColumn: 'uri',
		sm: blobs_sm,
		bbar: new Ext.Toolbar(
		{
			margins: '5 5 5 5',
			items: [
			{
				id: 'refreshblobsbutton',
				iconCls: 'refresh-icon',
				handler: function(button, event)
				{
					blobs_grid.getStore().reload();
				}
			},
			'-',
			{
				id: 'uploaddialogbutton',
				text: 'Upload files',
				iconCls: 'computer-add-icon',
				disabled: true,
				handler: open_upload_dialog
			},
			'-',
			{
				id: 'deleteblobbutton',
				text: 'Delete selected',
				iconCls: 'delete-icon',
				disabled: true,
				handler: function(button, event)
				{
					var rec = blobs_grid.getSelectionModel().getSelected();

					if (!rec)
						return;

					Ext.Ajax.request(
					{
						url: '/Home/DeleteBlob',
						method: 'DELETE',
						params:
						{
							container: blobs_grid.containerName,
							name: rec.data.name
						},
						success: function(response)
						{
							var result = Ext.decode(response.responseText);

							if (result.rc)
								blobs_grid.getStore().reload();
							else Ext.Msg.alert('Failed to delete BLOB', result.text);
						}
					});
				}
			}
			]
		})
	});

	var tables_sm = new Ext.grid.RowSelectionModel({ singleSelect: true });
	tables_sm.on('selectionchange', table_selected);

	tables_grid = new Ext.grid.GridPanel(
	{
		id: 'tables',
		title: 'Tables',
		iconCls: 'dbtables-icon',
		padding: '0 0 0 0',
		margin: '5 5 5 5',
		frame: false,
		border: false,
		stripeRows: true,
		viewConfig: { forceFit: true },
		store: new Ext.data.Store(
		{
			proxy: new Ext.data.HttpProxy({ url: '/Home/ListTables' }),
			reader: new Ext.data.JsonReader(
				{ root: 'tables', totalProperty: 'total' },
				Ext.data.Record.create([{ name: 'name'}])
			),
			sortInfo: { field: 'name', direction: "ASC" },
			remoteSort: false
		}),
		cm: new Ext.grid.ColumnModel(
		[
			{ id: 'name', header: 'Name', dataIndex: 'name', sortable: true, width: 300 }
		]),
		autoExpandColumn: 'name',
		sm: tables_sm,
		bbar: new Ext.Toolbar(
		{
			margins: '5 5 5 5',
			items: [
			{
				iconCls: 'refresh-icon',
				handler: function(button, event)
				{
					tables_grid.getStore().reload();
				}
			},
			'-',
			{
				xtype: 'textfield',
				id: 'newtablename',
				emptyText: 'Enter table name'
			},
			' ',
			{
				text: 'Create table',
				iconCls: 'add-icon',
				handler: function(button, event)
				{
					Ext.Ajax.request({
						url: '/Home/CreateTable',
						method: 'POST',
						params:
						{
							name: Ext.getCmp('newtablename').getValue()
							//isPublic: Ext.getCmp('newblobcontainerispublic').getValue()
						},
						success: function(response)
						{
							var result = Ext.decode(response.responseText);

							if (result.rc)
								tables_grid.getStore().reload();
							else Ext.Msg.alert('Failed to create table', result.text);
						}
					});
				}
			},
			'-',
			{
				id: 'deletetablebutton',
				text: 'Delete selected',
				iconCls: 'delete-icon',
				disabled: true,
				handler: function(button, event)
				{
					var rec = tables_grid.getSelectionModel().getSelected();

					if (!rec)
						return;

					Ext.Ajax.request(
					{
						url: '/Home/DeleteTable',
						method: 'DELETE',
						params:
						{
							name: rec.data.name
						},
						success: function(response)
						{
							var result = Ext.decode(response.responseText);

							if (result.rc)
								tables_grid.getStore().reload();
							else Ext.Msg.alert('Failed to delete table', result.text);
						}
					});
				}
			}
			]
		})
	});

	var table_entities_sm = new Ext.grid.RowSelectionModel({ singleSelect: true });
	table_entities_sm.on('selectionchange', table_entity_selected);

	var table_entities_store = new Ext.data.Store({
		proxy: new Ext.data.HttpProxy({ url: '/Home/ListTableEntities' }),
		reader: new Ext.data.JsonReader(
			{ root: 'entities', totalProperty: 'total' },
			Ext.data.Record.create([{ name: 'partition_key' }, { name: 'row_key'}])
		),
		remoteSort: false
	});

	table_entities_store.addListener("metachange", function(store, meta)
	{
		var columns = [];

		for (var i = 0; i < meta.fields.length; ++i)
			columns.push({ header: meta.fields[i].name, dataIndex: meta.fields[i].name, width: 160 });

		table_entities_grid.reconfigure(table_entities_store, new Ext.grid.ColumnModel(columns));
	});
	
	function show_create_entities_dialog(button, event)
	{
		if (!table_entities_grid.tableName)
			return;

		var entity_dialog = entities_dialogs[table_entities_grid.tableName];
		
		if( !entity_dialog )
		{
			var entity = table_entities_grid.getSelectionModel().getSelected();

			var create_entities_store = new Ext.data.Store({
				autoDestroy: true,
				reader: new Ext.data.ArrayReader(
					{idIndex:0},
					Ext.data.Record.create([{name: 'name'}, {name: 'value'}])
				)
			});

			entities_grid_panel = new Ext.grid.EditorGridPanel({
				autoExpandColumn: 'value',
				padding: '0 0 0 0',
				margin: '5 5 5 5',
				frame: false,
				border: false,
				stripeRows: true,
				clicksToEdit: 1,
				viewConfig: { forceFit: true },
				sm: new Ext.grid.RowSelectionModel({ singleSelect: true }),
				cm: new Ext.grid.ColumnModel(
				[
					{ 
						id: 'name', header: 'Column name', dataIndex: 'name', sortable: false, width: 200,
						editor: new Ext.form.TextField({
							allowBlank: false
						})
					},
					{
						id: 'value', header: 'Value', dataIndex: 'value', sortable: false, width: 300,
						editor: new Ext.form.TextField({
							allowBlank: false
						})
					}
				]),
				store: create_entities_store,
				bbar: new Ext.Toolbar({
					margins: '5 5 5 5',
					items: [
						{
							text: 'Add column',
							iconCls: 'add-icon',
							handler: function(button, event) {
								this.apanel.stopEditing();
								var rt = this.apanel.getStore().recordType;
								var r = new rt({name: '',value: ''});
								this.apanel.getStore().insert(0, r);
								this.apanel.startEditing(0,0);
							}
						},
						{
							text: 'Delete column',
							iconCls: 'delete-icon',
							handler: function(button, event) {
								var selected = this.apanel.getSelectionModel().getSelected();

								if( !selected )
									return;

								if( selected.data.name == 'PartitionKey' || selected.data.name == 'RowKey' )
								{
									Ext.Msg.alert("Can't remove", 'Partition key and row key are mandatory columns');
									return;
								}

								this.apanel.stopEditing();
								this.apanel.getStore().remove(selected);
							}
						},
						'-',
						{
							text: 'Insert entity',
							iconCls: 'dbsave-icon',
							handler: function(button, event) {
								var parameters = { __table_name__: table_entities_grid.tableName };

								this.apanel.getStore().each(function(record) {
									if( record.data.name )
										parameters[record.data.name] = record.data.value;
								});

								Ext.Ajax.request(
								{
									url: '/Home/CreateTableEntity',
									method: 'POST',
									params: parameters,
									success: function(response)
									{
										var result = Ext.decode(response.responseText);

										if (result.rc)
											table_entities_grid.getStore().reload();
										else Ext.Msg.alert('Failed to create entity', result.text);
									}
								});
							}
						}
					]
				})
			});

			entities_grid_panel.getBottomToolbar().items.each(function (item) { item.apanel = entities_grid_panel; });

			entity_dialog = new Ext.Window({
				title: 'Create entity in table [' + table_entities_grid.tableName + ']',
				width: 600,
				height: 400,
				iconCls: 'new-entity-icon',
				closable: true,
				closeAction: 'hide',
				modal: true,
				frame: true,
				layout: 'fit',
				items: [entities_grid_panel]
			});

			if( entity )
			{
				var columns = [];

				for(name in entity.data)
					columns.push([name, entity.data[name]]);
				create_entities_store.loadData(columns);
			}
			else
			{
				create_entities_store.loadData([
					['PartitionKey', ''],
					['RowKey', '']
				]);
			}

			entities_dialogs[table_entities_grid.tableName] = entity_dialog;

			entity_dialog.on('hide', function(panel) {table_entities_grid.getStore().reload();});
		}

		entity_dialog.show();
	}

	table_entities_grid = new Ext.grid.GridPanel({
		id: 'table_entities',
		title: 'Entities - table not selected',
		iconCls: 'entities-icon',
		padding: '0 0 0 0',
		margin: '5 5 5 5',
		frame: false,
		border: false,
		stripeRows: true,
		viewConfig: { /*forceFit: true*/ autoFill: true },
		//loadMask: true,
		maskDisabled: false,
		store: table_entities_store,
		cm: new Ext.grid.ColumnModel(
		[
			{ id: 'PartitionKey', header: 'PartitionKey', dataIndex: 'PartitionKey', sortable: true, width: 300 },
			{ id: 'RowKey', header: 'RowKey', dataIndex: 'RowKey', sortable: true, width: 300 }
		]),
		sm: table_entities_sm,
		bbar: new Ext.Toolbar(
		{
			margins: '5 5 5 5',
			items: [
			{
				id: 'refreshentitiesbutton',
				iconCls: 'refresh-icon',
				handler: function(button, event)
				{
					table_entities_grid.getStore().reload();
				}
			},
			'-',
			{
				id: 'createentity',
				text: 'Create entities',
				iconCls: 'add-icon',
				disabled: true,
				handler: show_create_entities_dialog
			},
			'-',
			{
				id: 'deleteentity',
				text: 'Delete selected',
				iconCls: 'delete-icon',
				disabled: true,
				handler: function(button, event)
				{
					var rec = table_entities_grid.getSelectionModel().getSelected();

					if (!rec)
						return;

					Ext.Ajax.request(
					{
						url: '/Home/DeleteTableEntity',
						method: 'DELETE',
						params:
						{
							table: table_entities_grid.tableName,
							partition_key: rec.data.PartitionKey,
							row_key: rec.data.RowKey
						},
						success: function(response)
						{
							var result = Ext.decode(response.responseText);

							if (result.rc)
								table_entities_grid.getStore().reload();
							else Ext.Msg.alert('Failed to delete entity', result.text);
						}
					});
				}
			}
			]
		})
	});

	var queues_sm = new Ext.grid.RowSelectionModel({ singleSelect: true });
	queues_sm.on('selectionchange', queue_selected);

	queues_grid = new Ext.grid.GridPanel(
	{
		id: 'queues',
		title: 'Queues',
		iconCls: 'queue-icon',
		padding: '0 0 0 0',
		margin: '5 5 5 5',
		frame: false,
		border: false,
		stripeRows: true,
		viewConfig: { forceFit: true },
		store: new Ext.data.Store(
		{
			proxy: new Ext.data.HttpProxy({ url: '/Home/ListQueues' }),
			reader: new Ext.data.JsonReader(
				{ root: 'queues', totalProperty: 'total' },
				Ext.data.Record.create([{ name: 'name' }, { name: 'uri' }, { name: 'approximate_count'}])
			),
			sortInfo: { field: 'name', direction: "ASC" },
			remoteSort: false
		}),
		cm: new Ext.grid.ColumnModel(
		[
			{ id: 'name', header: 'Name', dataIndex: 'name', sortable: true, width: 240 },
			{ id: 'uri', header: 'Uri', dataIndex: 'uri', sortable: true, width: 300, xtype: 'templatecolumn', tpl: new Ext.XTemplate('<a href="{uri}?comp=metadata" target="_blank">{uri}</a>') },
			{ id: 'approximate_count', header: 'Approx. #', dataIndex: 'approximate_count', sortable: true, width: 80 }
		]),
		autoExpandColumn: 'uri',
		sm: queues_sm,
		bbar: new Ext.Toolbar(
		{
			margins: '5 5 5 5',
			items: [
			{
				iconCls: 'refresh-icon',
				handler: function(button, event)
				{
					queues_grid.getStore().reload();
				}
			},
			'-',
			{
				xtype: 'textfield',
				id: 'newqueuename',
				emptyText: 'Enter queue name'
			},
			' ',
			{
				text: 'Create queue',
				iconCls: 'add-icon',
				handler: function(button, event)
				{
					Ext.Ajax.request(
					{
						url: '/Home/CreateQueue',
						method: 'POST',
						params:
						{
							name: Ext.getCmp('newqueuename').getValue()
						},
						success: function(response)
						{
							var result = Ext.decode(response.responseText);

							if (result.rc)
								queues_grid.getStore().reload();
							else Ext.Msg.alert('Failed to create queue', result.text);
						}
					});
				}
			},
			'-',
			{
				id: 'deletequeuebutton',
				text: 'Delete selected',
				iconCls: 'delete-icon',
				disabled: true,
				handler: function(button, event)
				{
					var rec = queues_grid.getSelectionModel().getSelected();

					if (!rec)
						return;

					Ext.Ajax.request(
					{
						url: '/Home/DeleteQueue',
						method: 'DELETE',
						params:
						{
							name: rec.data.name
						},
						success: function(response)
						{
							var result = Ext.decode(response.responseText);

							if (result.rc)
								queues_grid.getStore().reload();
							else Ext.Msg.alert('Failed to delete queue', result.text);
						}
					});
				}
			}
			]
		})
	});

	log_pulled_message = function(text)
	{
		var d = new Date();
		var h = d.getHours();
		var m = d.getMinutes();
		var s = d.getSeconds();

		var formatted_msg = '<font color="#993333">' + ((h < 10) ? '0' : '') + h + ((m < 10) ? ':0' : ':') + m + ((s < 10) ? ':0' : ':') + s +
			': </font><font color="#333399">"' + text + '"</font><br>';

		Ext.get('pulled_messages').dom.innerHTML = formatted_msg + Ext.get('pulled_messages').dom.innerHTML;
	}

	queue_messages_grid = new Ext.grid.GridPanel({
		id: 'queue_messages',
		title: 'Top messages - queue not selected',
		iconCls: 'queue-messages-icon',
		padding: '0 0 0 0',
		margin: '5 5 5 5',
		frame: false,
		border: false,
		stripeRows: true,
		viewConfig: { forceFit: true },
		store: new Ext.data.Store(
		{
			proxy: new Ext.data.HttpProxy({ url: '/Home/ListTopQueueMessages' }),
			reader: new Ext.data.JsonReader(
				{ root: 'messages', totalProperty: 'total' },
				Ext.data.Record.create([{ name: 'id' }, { name: 'content' }, { name: 'created' }, { name: 'expires'}])
			),
			remoteSort: false
		}),
		cm: new Ext.grid.ColumnModel(
		[
			{ id: 'id', header: 'Id', dataIndex: 'id', sortable: false, width: 240 },
			{ id: 'content', header: 'Content', dataIndex: 'content', sortable: false, width: 300 },
			{ id: 'created', header: 'Created', dataIndex: 'created', sortable: false, width: 140 },
			{ id: 'expires', header: 'Expires', dataIndex: 'expires', sortable: false, width: 140 }
		]),
		autoExpandColumn: 'content',
		sm: new Ext.grid.RowSelectionModel({ singleSelect: true }),
		bbar: new Ext.Toolbar(
		{
			margins: '5 5 5 5',
			items: [
			{
				id: 'refreshqueuemessagesbutton',
				iconCls: 'refresh-icon',
				handler: function(button, event)
				{
					queue_messages_grid.getStore().reload();
				}
			},
			'-',
			{
				id: 'queuemessagecontent',
				xtype: 'textfield',
				emptyText: 'Enter message content',
				width: 300
			},
			{
				id: 'createqueuemessage',
				text: 'Put text message',
				iconCls: 'message-add-icon',
				disabled: true,
				handler: function(button, event)
				{
					var rec = queues_grid.getSelectionModel().getSelected();

					if (!rec)
						return;

					Ext.Ajax.request(
					{
						url: '/Home/PutQueueMessage',
						params:
						{
							queue: rec.data.name,
							content: Ext.getCmp('queuemessagecontent').getValue()
						},
						success: function(response)
						{
							var result = Ext.decode(response.responseText);

							if (result.rc)
								queue_messages_grid.getStore().reload();
							else Ext.Msg.alert('Failed to put message', result.text);
						}
					});
				}
			},
			{
				id: 'uploadbinarymsgbutton',
				text: 'Upload binary messages',
				iconCls: 'computer-add-icon',
				disabled: true,
				handler: open_upload_binary_msg_dialog
			},
			'-',
			{
				id: 'getqueuemessage',
				text: 'Get message',
				iconCls: 'message-delete-icon',
				disabled: true,
				handler: function(button, event)
				{
					Ext.Ajax.request(
					{
						url: '/Home/GetQueueMessage',
						params:
						{
							queue: queue_messages_grid.queueName
						},
						success: function(response)
						{
							var result = Ext.decode(response.responseText);

							if (result.rc)
							{
								queue_messages_grid.getStore().reload();

								log_pulled_message(result.text);
							}
							else if (result.text != '')
								Ext.Msg.alert('Failed to get queue message', result.text);
						}
					});
				}
			}
			]
		})
	});

	show_help = function(event, toolEl, panel)
	{
		help_dialog = new Ext.Window({
			title: 'ExploAzure - Storage Manager',
			iconCls: 'storage-icon',
			padding: '15 15 15 15',
			width: 500,
			tools: [{ id: 'gear', handler: function(event, toolEl, panel) { Ext.log('Ext debug console activated.'); } }],
			html: '<div><h1>ExploAzure - Storage Manager, version 1.0</h1><br><p><a href="http://exploazure.codeplex.com/">ExploAzure</a> is a Windows Azure storage manager that allows monitoring content of your cloud storage or your local developement storage. You can create and delete BLOB containers, BLOBs (upload files), tables, table entities and queues, monitor content of queues (peek top messages), put messages into queues and get messages from queues. This allows for easy testing of applications that utilize Windows Azure cloud storage.</p><br><p>ExploAzure Storage Manager can itself run in the cloud. It utilizes ASP.Net MVC, Azure Storage Client (MS sample) and ExtJS for AJAX user interface.</p><br><p>By <a href="mailto:rbc@genesyslab.com">Michael Rybachenko</a></p><br><p>Thanks to:</p><br><p><a href="http://www.extjs.com" target="_blank">www.extjs.com</a> for great framework</p><br><p><a href="http://blogs.msdn.com/jnak/archive/2008/10/28/asp-net-mvc-projects-running-on-windows-azure.aspx" target="_blank">Jim Nakashima (blogs.msdn.com/jnak)</a> for MVC in the cloud</p><br><p><a href="http://www.max-bazhenov.com/dev/upload-dialog-2.0/index.php" target="_blank">Max Bazhenov</a> for file upload dialog</p><br><p><a href="http://msdn.microsoft.com/en-us/azure/dd327650.aspx" target="_blank">Bill Lodin</a> for Azure Storage screencasts</p></div>'
		});

		help_dialog.show(toolEl);
	}
	
	show_account_dialog = function()
	{
		if( !account_dialog )
		{
			var use_cloud_fieldset = new Ext.form.FieldSet({
				id: 'use_cloud_field',
				xtype: 'fieldset',
				checkboxToggle: true,
				title: 'Use cloud storage',
				autoHeight: true,
				defaults: { width: 250 },
				defaultType: 'textfield',
				collapsed: false,
				items: [
					{
						id: 'account_name_field',
						fieldLabel: 'Account name',
						name: 'account_name',
						allowBlank: true
					},
					{
						id: 'account_key_field',
						fieldLabel: 'Shared key',
						name: 'account_key',
						allowBlank: true
					}
				]
			});

			var use_dev_fieldset = new Ext.form.FieldSet({
				id: 'use_dev_field',
				xtype: 'fieldset',
				checkboxToggle: true,
				title: 'Use development storage',
				autoHeight: true,
				defaults: { width: 250 },
				defaultType: 'textfield',
				collapsed: true,
				items: [
					{
						id: 'storage_addr_field',
						fieldLabel: 'Connect to',
						name: 'storage_addr',
						emptyText: 'http://127.0.0.1',
						allowBlank: true
					},
					{ xtype: 'label', text: 'Leave blank to use local development storage'}
				]
			});

			use_cloud_fieldset.on('expand', function() {Ext.getCmp('use_dev_field').collapse();});
			use_dev_fieldset.on('expand', function() {Ext.getCmp('use_cloud_field').collapse();});
			use_cloud_fieldset.on('collapse', function() {Ext.getCmp('use_dev_field').expand();});
			use_dev_fieldset.on('collapse', function() {Ext.getCmp('use_cloud_field').expand();});

			var account_form = new Ext.form.FormPanel({
				defaultType: 'textfield',
				bodyStyle: 'padding:5px 5px 0',
				labelWidth: 120,
				frame: true,
				items: [use_cloud_fieldset, use_dev_fieldset, 
					{ xtype: 'label', html: '<img src="../../Content/icons/secured.png">'}
					//{ xtype: 'label', html: '<span id="siteseal"><script type="text/javascript" src="https://seal.godaddy.com/getSeal?sealID=4y8KRJsbfdq9NdCPY2uGGkDqvHhe3Q1WT7vfVcZEqMqRSQmV2vvTC"/><br/><a style="font-family: arial; font-size: 9px" href="https://www.godaddy.com/gdshop/ssl/ssl.asp" target="_blank">Secure Servers</a></span>'}
				],
				buttons: [
					{
						text: "Let's go!",
						handler: function(button, event)
						{
							Ext.Ajax.request(
							{
								url: '/Home/SetAccount',
								method: 'POST',
								params:
								{
									use_development: Ext.getCmp('use_cloud_field').collapsed,
									account_name: Ext.getCmp('account_name_field').getValue(),
									account_key: Ext.getCmp('account_key_field').getValue(),
									storage_addr: Ext.getCmp('storage_addr_field').getValue()
								},
								success: function(response)
								{
									var result = Ext.decode(response.responseText);

									if (result.rc)
									{
										account_needed = false;

										var account_name = Ext.getCmp('use_cloud_field').collapsed ? "devstoreaccount1" : Ext.getCmp('account_name_field').getValue();

										if( !account_name )
											account_name = '';

										Ext.getCmp('titlePanel').setTitle('ExploAzure - Storage Manager' + (account_name ? ' - ' : '') + account_name);
										blob_containers_grid.getStore().reload();
										tables_grid.getStore().reload();
										queues_grid.getStore().reload();
										account_dialog.hide();
									}
									else
									{
										blob_containers_grid.getStore().removeAll();
										tables_grid.getStore().removeAll();
										queues_grid.getStore().removeAll();

										if (result.text != '')
											Ext.Msg.alert('Error', result.text);
									}
								}
							});
						}
					}
				]
			});

			account_dialog = new Ext.Window({
				title: 'Account information',
				iconCls: 'account-icon',
				height: 310,
				width: 430,
				closable: true,
				modal: true,
				layout: 'fit',
				items: [account_form]
			});
		}

		account_dialog.show();
	};

	var viewport = new Ext.Viewport(
	{
		layout: 'border',
		padding: '5 5 5 5',
		margin: '0 0 0 0',
		defaults:
		{
			margin: '0 0 0 0',
			padding: '0 0 0 0'
		},
		items: [
		{
			id: 'titlePanel',
			region: 'north',
			title: 'ExploAzure - Storage Manager',
			iconCls: 'storage-icon',
			tools: [
				{ id: 'gear', handler: function() { show_account_dialog(); } },
				{ id: 'help', handler: show_help }
			]
		},
		{
			id: 'mainPanel',
			region: 'center',
			border: false,
			footer: false,
			xtype: 'tabpanel',
			activeItem: 0,
			items: [
			{
				id: 'panelBlobs',
				title: 'Blobs',
				iconCls: 'blob-icon',
				layout: { type: 'border', align: 'stretch' },
				border: false,
				items: [
				{
					region: 'north',
					border: true,
					height: 350,
					flex: 1,
					split: true,
					layout: 'fit',
					items: [blob_containers_grid]
				},
				{
					region: 'center',
					border: true,
					flex: 2,
					split: true,
					layout: 'fit',
					items: [blobs_grid]
				}
				]
			},
			{
				id: 'panelTables',
				title: 'Tables',
				iconCls: 'dbtables-icon',
				layout: { type: 'border', align: 'stretch' },
				border: false,
				items: [
				{
					region: 'north',
					border: true,
					height: 280,
					flex: 1,
					split: true,
					layout: 'fit',
					items: [tables_grid]
				},
				{
					region: 'center',
					border: true,
					flex: 2,
					split: true,
					layout: 'fit',
					items: [table_entities_grid]
				}
				]
			},
			{
				id: 'panelQueues',
				title: 'Queues',
				iconCls: 'queue-icon',
				layout: { type: 'border', align: 'stretch' },
				border: false,
				items: [
				{
					region: 'north',
					border: true,
					height: 280,
					flex: 1,
					split: true,
					layout: 'fit',
					items: [queues_grid]
				},
				{
					region: 'center',
					border: true,
					flex: 2,
					split: true,
					layout: 'fit',
					items: [queue_messages_grid]
				},
				{
					region: 'south',
					border: true,
					split: true,
					title: 'Pulled messages',
					autoScroll: true,
					height: 120,
					collapsible: true,
					flex: 1,
					padding: '5 5 5 5',
					html: '<div style="font-size: .75em" id="pulled_messages"></div>'
				}
				]
			}
			]
		}
		]
	});

	var loading = Ext.get('loading');
	var mask = Ext.get('loading-mask');
	mask.remove();
	loading.remove();
	Ext.get(document.body).setStyle('overflow', 'visible');
	Ext.get(document.body).setStyle('overflow', 'auto');

	if (!account_needed)
	{
		blob_containers_grid.getStore().reload();
		tables_grid.getStore().reload();
		queues_grid.getStore().reload();
	}
	else
	{
		show_account_dialog();
	}
});
</script>
</asp:Content>
<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">
</asp:Content>
